<?php

namespace Gds\AchatBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Gds\AchatBundle\Entity\BonLivraisonFournisseur;
use Gds\AchatBundle\Form\BonLivraisonFournisseurType;
use Gds\AchatBundle\Entity\LigneBonLivraisonFournisseur;
use Symfony\Component\HttpFoundation\Response;
use Gds\AchatBundle\Entity\StockAchat;
use Gds\VenteBundle\Entity\CategorieRemise;
use Gds\VenteBundle\Entity\FactureClient;
use Symfony\Component\Validator\Constraints\Date;
use Gds\AchatBundle\Entity\CategorieRemiseFournisseur;
use Gds\AchatBundle\Entity\FactureFournisseur;
use Gds\AchatBundle\Form\FactureFournisseurType;

class BonLivraisonController extends Controller {

    public function getArticlesWhereFamillesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $fournisseur_id = $request->get('fournisseur_id');
        $fournisseur = $em->getRepository('GdsAchatBundle:Fournisseur')->find($fournisseur_id);
        $familles = json_decode($request->get('familles'));
        $sous_familles = $familles->sous_familles;
        if (count($sous_familles) == 0) {
            $familles = $familles->familles;
            $all_familles = $familles;
            foreach ($familles as $famille) {
                $sous_familles = $em->getRepository('GdsArticleBundle:Famille')->findBy(array('famille_mere' => $famille, 'is_supprimer' => 0));
                foreach ($sous_familles as $sous_famille)
                    array_push($all_familles, $sous_famille->getId());
            }
            $familles = $all_familles;
        }
        else
            $familles = $familles->sous_familles;
        $result = array();
        $k = 0;
        foreach ($familles as $id_famille) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findByFamille($id_famille);
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['taux_tva'] = $article->getTauxTva();
                    $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                    if ($categorie_remise != null) {
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                        $result[$k]['prix_achat'] = $categorie_remise->getPrixUnitaireHt();
                    } else {
                        $result[$k]['remise'] = 0;
                        $result[$k]['prix_achat'] = $article->getPrixAchatHt();
                    }
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        if (count($familles) == 0) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['taux_tva'] = $article->getTauxTva();
                    $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                    if ($categorie_remise != null) {
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                        $result[$k]['prix_achat'] = $categorie_remise->getPrixAchatHt();
                    } else {
                        $result[$k]['remise'] = 0;
                        $result[$k]['prix_achat'] = $article->getPrixAchatHt();
                    }
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $bon_livraison = new BonLivraisonFournisseur();
        $request = $this->getRequest();
        $form = $this->createForm(new BonLivraisonFournisseurType(), $bon_livraison);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                if (count($articles->articles) == 0) {
                    $response = new Response(json_encode(array('success' => false)));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_livraison = $form->getData();
                $fournisseur = $bon_livraison->getFournisseur();
                $is_facturable = $request->get('facturable');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $bon_livraison->setHeure($heure);
                if ($is_facturable == 'true')
                    $bon_livraison->setIsFacturable(true);
                else
                    $bon_livraison->setIsFacturable(false);
                $bon_livraison->setIsSupprimer(false);
                $bon_livraison->setIsCloturer(false);
                $montant_ttc = 0;
                foreach ($articles->articles as $json_article) {
                    $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                    $prix_achat_ttc = $json_article->prix_achat * (1 + ($json_article->taux_tva / 100)) * (1 - ($json_article->remise / 100));
                    $montant_ttc = $montant_ttc + ($prix_achat_ttc * $json_article->quantite);
                    if ($is_facturable == 'true') {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'is_noir' => 0, 'prix_achat_ttc' => $prix_achat_ttc));
                        if (!$stock_achat) {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(false);
                            $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                            $stock_achat->setQuantite($json_article->quantite);
                            $stock_achat->setStock($stock);
                        } else {
                            $stock_achat->setQuantite($stock_achat->getQuantite() + $json_article->quantite);
                        }
                        $stock->setQuantiteBlanc($stock->getQuantiteBlanc() + $json_article->quantite);
                    } else {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 1, 'prix_achat_ttc' => $prix_achat_ttc));
                        if (!$stock_achat) {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(TRUE);
                            $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                            $stock_achat->setQuantite($json_article->quantite);
                            $stock_achat->setStock($stock);
                        } else {
                            $stock_achat->setQuantite($stock_achat->getQuantite() + $json_article->quantite);
                        }
                        $stock->setQuantiteNoir($stock->getQuantiteNoir() + $json_article->quantite);
                    }
                    $em->persist($stock_achat);
                    $em->persist($stock);
                    $taux_tva = $json_article->taux_tva;
                    $remise = $json_article->remise;
                    $ligne = new LigneBonLivraisonFournisseur();
                    $ligne->setArticle($article);
                    $ligne->setQuantite($json_article->quantite);
                    $ligne->setQuantiteRetour(0);
                    $ligne->setPrixUnitaireHt($json_article->prix_achat);
                    $ligne->setTauxRemise($remise);
                    $ligne->setTauxTva($taux_tva);
                    $bon_livraison->addLigne($ligne);
                    $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                    if ($categorie_remise != null) {
                        $categorie_remise->setRemise($remise);
                        $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                    } else {
                        $categorie_remise = new CategorieRemiseFournisseur();
                        $categorie_remise->setArticle($article);
                        $categorie_remise->setFournisseur($fournisseur);
                        $categorie_remise->setRemise($remise);
                        $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                        $em->persist($categorie_remise);
                    }
                }
                $bon_livraison->setDepartement($departement);
                $bon_livraison->setReste($montant_ttc);
                $bon_livraison->setMontantTtc($montant_ttc);
                $bon_livraison->setUser($user);
                $em->persist($bon_livraison);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        return $this->render('GdsAchatBundle:BonLivraison:bon_livraison.html.twig', array('form' => $form->createView(), 'user' => $user));
    }

    public function getAllBonLivraisonAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $num = $request->get('numero');
        $fournisseur = $request->get('fournisseur');
        $date1 = $request->get('date1');
        $date2 = $request->get('date2');
        $heure1 = $request->get('heure1');
        $heure2 = $request->get('heure2');
        $ref = $request->get('reference');
        $des = $request->get('designation');
        $ttc1 = $request->get('ttc1');
        $ttc2 = $request->get('ttc2');
        $is_cloturer = $request->get('is_cloture');
        $reglement = $request->get('reglement');
        $departement = $request->get('departement');
        $user = $this->getUser();
        if (!$request->get('type') && !$request->get('retour'))
            $departement = $user->getDepartement()->getId();
        if ($is_cloturer == 2)
            $is_cloturer = '';
        $query = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->getResult($num, $fournisseur, $date1, $date2, $heure1, $heure2, $ref, $des, $ttc1, $ttc2, $is_cloturer, $reglement, $departement);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );

        if ($request->get('type')) {
            return $this->render('GdsAchatBundle:BonLivraison:page_liste_bon_livraison.html.twig', array('pagination' => $pagination, 'departement' => $departement));
        }
        if ($request->get('retour') != "")
            return $this->render('GdsAchatBundle:BonLivraison:liste_bon_livraison.html.twig', array('pagination' => $pagination, 'departement' => $departement));
        return $this->render('GdsAchatBundle:BonLivraison:all_bon_livraison.html.twig', array('pagination' => $pagination, 'departement' => $user->getDepartement()->getId()));
    }

    public function showAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $bon_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->find($id);
        $lignes_bon_livraison = $em->getRepository('GdsAchatBundle:LigneBonLivraisonFournisseur')->findBy(array('bon_livraison' => $bon_livraison));
        $lignes = $em->getRepository('GdsAchatBundle:LigneBonLivraisonFournisseur')->findBy(array('bon_livraison' => $bon_livraison), array('taux_tva' => 'ASC'));
        $taxes = array();
        foreach ($lignes as $ligne) {
            $tva = $ligne->getTauxTva();
            $base = $ligne->getQuantite() * $ligne->getPrixUnitaireHt() * (1 - $ligne->getTauxRemise() / 100);
            $montant = $base * $tva / 100;
            $exist = false;
            foreach ($taxes as $k => $taxe) {
                if (!$exist && $taxe['tva'] == $tva) {
                    $taxes[$k]['base']+=$base;
                    $taxes[$k]['montant']+=$montant;
                    $exist = true;
                }
            }
            if (!$exist) {
                $taxe = array();
                $taxe['tva'] = $tva;
                $taxe['base'] = $base;
                $taxe['montant'] = $montant;
                $taxes[count($taxes)] = $taxe;
            }
        }
        return $this->render('GdsAchatBundle:BonLivraison:bon_livraison_show.html.twig', array('bon_livraison' => $bon_livraison, 'lignes' => $lignes_bon_livraison, 'taxes' => $taxes));
    }

    public function editAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $bon_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->find($id);
        $form = $this->createForm(new BonLivraisonFournisseurType, $bon_livraison);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            $articles = json_decode($request->get('articles'));
            if (count($articles->articles) == 0) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
            $departement = $bon_livraison->getDepartement();
            $stocks = array();
            foreach ($bon_livraison->getLignes() as $ligne) {
                $article = $ligne->getArticle();
                $quantite = $ligne->getQuantite();
                $prix_achat_ht = $ligne->getPrixUnitaireHt();
                $tva = $ligne->getTauxTva();
                $remise = $ligne->getTauxRemise();
                $prix_achat_ttc = $prix_achat_ht * (1 + ($tva / 100)) * (1 - ($remise / 100));
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('departement' => $departement, 'article' => $article));
                if ($bon_livraison->getIsFacturable()) {
                    $quantite_stock_blanc = $stock->getQuantiteBlanc();
                    $stock->setQuantiteBlanc($quantite_stock_blanc - $quantite);
                    $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'prix_achat_ttc' => $prix_achat_ttc, 'is_noir' => 0));
                } else {
                    $quantite_stock_noir = $stock->getQuantiteNoir();
                    $stock->setQuantiteNoir($quantite_stock_noir - $quantite);
                    $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'prix_achat_ttc' => $prix_achat_ttc, 'is_noir' => 1));
                }
                $ecart = $quantite;
                if ($stock_achat != null) {
                    if ($stock_achat->getQuantite() - $ecart > 0) {
                        $stock_achat->setQuantite($stock_achat->getQuantite() - $ecart);
                        $em->persist($stock_achat);
                        $ecart = 0;
                    } elseif ($stock_achat->getQuantite() - $ecart == 0) {
                        $ecart = 0;
                        $em->remove($stock_achat);
                    } else {
                        $em->remove($stock_achat);
                        $ecart = $ecart - $stock_achat->getQuantite();
                    }
                }
                if ($ecart > 0) {
                    if ($bon_livraison->getIsFacturable()) {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'ASC', 'prix_achat_ttc' => 'ASC'));
                    } else {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
                    }
                    $i = 0;
                    while ($ecart > 0 && $i < count($stock_achat)) {
                        if ($ecart < $stock_achat[$i]->getQuantite()) {
                            $stock_achat[$i]->setQuantite($stock_achat[$i]->getQuantite() - $ecart);
                            $em->persist($stock_achat[$i]);
                            $ecart = 0;
                        } else {
                            if ($ecart == $stock_achat[$i]->getQuantite())
                                $em->remove($stock_achat[$i]);
                            else {
                                $em->remove($stock_achat[$i]);
                                $ecart = $ecart - $stock_achat[$i]->getQuantite();
                            }
                        }
                        $i++;
                    }
                }
                $em->remove($ligne);
                $em->flush();
            }
            $heure = $request->get('heure');
            $form->bind($request);
            $bon_livraison = $form->getData();
            $is_facturable = $request->get('facturable');
            $bon_livraison->setIsfacturable($is_facturable);
            $fournisseur = $bon_livraison->getFournisseur();
            $bon_livraison->setHeure($heure);
            $montant_ttc = 0;
            foreach ($articles->articles as $json_article) {
                $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                $prix_achat_ttc = $json_article->prix_achat * (1 + ($json_article->taux_tva / 100)) * (1 - ($json_article->remise / 100));
                $montant_ttc = $montant_ttc + ($prix_achat_ttc * $json_article->quantite);
                if ($is_facturable == 'true') {
                    $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'is_noir' => 0, 'prix_achat_ttc' => $prix_achat_ttc));
                    if (!$stock_achat) {
                        $stock_achat = new StockAchat();
                        $stock_achat->setIsNoir(false);
                        $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                        $stock_achat->setQuantite($json_article->quantite);
                        $stock_achat->setStock($stock);
                    }
                    $stock->setQuantiteBlanc($stock->getQuantiteBlanc() + $json_article->quantite);
                } else {
                    $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 1, 'prix_achat_ttc' => $prix_achat_ttc));
                    if (!$stock_achat) {
                        $stock_achat = new StockAchat();
                        $stock_achat->setIsNoir(TRUE);
                        $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                        $stock_achat->setQuantite($json_article->quantite);
                        $stock_achat->setStock($stock);
                    }
                    $stock->setQuantiteNoir($stock->getQuantiteNoir() + $json_article->quantite);
                }
                $em->persist($stock_achat);
                $em->persist($stock);
                $taux_tva = $json_article->taux_tva;
                $remise = $json_article->remise;
                $ligne = new LigneBonLivraisonFournisseur();
                $ligne->setArticle($article);
                $ligne->setQuantite($json_article->quantite);
                $ligne->setQuantiteRetour(0);
                $ligne->setPrixUnitaireHt($json_article->prix_achat);
                $ligne->setTauxRemise($remise);
                $ligne->setTauxTva($taux_tva);
                $bon_livraison->addLigne($ligne);
                $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                if ($categorie_remise != null) {
                    $categorie_remise->setRemise($remise);
                    $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                } else {
                    $categorie_remise = new CategorieRemiseFournisseur();
                    $categorie_remise->setArticle($article);
                    $categorie_remise->setFournisseur($fournisseur);
                    $categorie_remise->setRemise($remise);
                    $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                    $em->persist($categorie_remise);
                }
            }
            $bon_livraison->setDepartement($departement);
            $bon_livraison->setReste($montant_ttc);
            $bon_livraison->setMontantTtc($montant_ttc);
            $bon_livraison->setUser($user);
            $em->persist($bon_livraison);
            $em->flush();
            $response = new Response(json_encode(array('success' => true)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $time = $bon_livraison->getTime();
        $heure = $bon_livraison->getHeure();
        $lignes = array();
        foreach ($bon_livraison->getLignes() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsAchatBundle:BonLivraison:bon_livraison_edit.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function duppliquerAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $old_bon_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->find($id);
        $bon_livraison = clone $old_bon_livraison;
        $bon_livraison->setReference('');
        $form = $this->createForm(new BonLivraisonFournisseurType, $bon_livraison);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                if (count($articles->articles) == 0) {
                    $response = new Response(json_encode(array('success' => false)));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_livraison = $form->getData();
                $fournisseur = $bon_livraison->getFournisseur();
                $is_facturable = $request->get('facturable');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $bon_livraison->setHeure($heure);
                $bon_livraison->setIsFacturable($is_facturable);
                $bon_livraison->setIsSupprimer(false);
                $bon_livraison->setIsCloturer(false);
                $montant_ttc = 0;
                foreach ($articles->articles as $json_article) {
                    $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                    $prix_achat_ttc = $json_article->prix_achat * (1 + ($json_article->taux_tva / 100)) * (1 - ($json_article->remise / 100));
                    $montant_ttc = $montant_ttc + ($prix_achat_ttc * $json_article->quantite);
                    if ($is_facturable == 'true') {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'is_noir' => 0, 'prix_achat_ttc' => $prix_achat_ttc));
                        if (!$stock_achat) {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(false);
                            $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                            $stock_achat->setQuantite($json_article->quantite);
                            $stock_achat->setStock($stock);
                        }
                        $stock->setQuantiteBlanc($stock->getQuantiteBlanc() + $json_article->quantite);
                    } else {
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 1, 'prix_achat_ttc' => $prix_achat_ttc));
                        if (!$stock_achat) {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(TRUE);
                            $stock_achat->setPrixAchatTtc($prix_achat_ttc);
                            $stock_achat->setQuantite($json_article->quantite);
                            $stock_achat->setStock($stock);
                        }
                        $stock->setQuantiteNoir($stock->getQuantiteNoir() + $json_article->quantite);
                    }
                    $em->persist($stock_achat);
                    $em->persist($stock);
                    $taux_tva = $json_article->taux_tva;
                    $remise = $json_article->remise;
                    $ligne = new LigneBonLivraisonFournisseur();
                    $ligne->setArticle($article);
                    $ligne->setQuantite($json_article->quantite);
                    $ligne->setQuantiteRetour(0);
                    $ligne->setPrixUnitaireHt($json_article->prix_achat);
                    $ligne->setTauxRemise($remise);
                    $ligne->setTauxTva($taux_tva);
                    $bon_livraison->addLigne($ligne);
                    $categorie_remise = $em->getRepository('GdsAchatBundle:CategorieRemiseFournisseur')->findOneBy(array('fournisseur' => $fournisseur, 'article' => $article));
                    if ($categorie_remise != null) {
                        $categorie_remise->setRemise($remise);
                        $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                    } else {
                        $categorie_remise = new CategorieRemiseFournisseur();
                        $categorie_remise->setArticle($article);
                        $categorie_remise->setFournisseur($fournisseur);
                        $categorie_remise->setRemise($remise);
                        $categorie_remise->setPrixUnitaireHt($json_article->prix_achat);
                        $em->persist($categorie_remise);
                    }
                }
                $bon_livraison->setDepartement($departement);
                $bon_livraison->setReste($montant_ttc);
                $bon_livraison->setMontantTtc($montant_ttc);
                $bon_livraison->setUser($user);
                $em->persist($bon_livraison);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $time = $bon_livraison->getTime();
        $heure = $bon_livraison->getHeure();
        $lignes = array();
        foreach ($bon_livraison->getLignes() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsAchatBundle:BonLivraison:bon_livraison_duppliquer.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $bon_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->find($id);
        $bon_livraison->setIsSupprimer(true);
        $em->persist($bon_livraison);
        $em->flush();
        return new Response('success');
    }

    public function facturerAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $timbre = $societe->getTimbreFiscal();
        $user = $this->getUser();
        $bon_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->find($id);
        $facture = new FactureFournisseur();
        $facture->setFournisseur($bon_livraison->getFournisseur());
        $facture->setUser($this->getUser());
        $form = $this->createForm(new FactureFournisseurType(), $facture);
        if ($request->isMethod('POST')) {

            $form->bind($request);
            $facture = $form->getData();
            $bon_livraison->setFacture($facture);
            $bon_livraison->setIsCloturer(true);
            $facture->setMontantTtc($bon_livraison->getMontantTtc() + $timbre);
            $facture->setReste($bon_livraison->getReste() + $timbre);
            $facture->setIsCloturer(false);
            $facture->setIsSupprimer(false);
            $heure = $request->get('heure');
            $facture->setHeure($heure);
            $facture->setUser($user);
            $em->persist($facture);
            $em->persist($bon_livraison);
            $em->flush();
            $response = new Response(json_encode(array('success' => true)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $lignes = array();
        foreach ($bon_livraison->getLignes() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsAchatBundle:BonLivraison:bon_livraison_to_facture.html.twig', array('form' => $form->createView(), 'lignes' => $lignes, 'id' => $id, 'timbre' => $timbre, 'bonlivraison' => $bon_livraison));
    }

    public function facturerPlusieursAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $ids_requested = $request->get('ids');
        $ids = json_decode($ids_requested);
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $timbre = $societe->getTimbreFiscal();
        $bons_livraison = $em->getRepository('GdsAchatBundle:BonLivraisonFournisseur')->findByIdIn($ids);
        $facture = new FactureFournisseur();
        $facture->setFournisseur($bons_livraison[0]->getFournisseur());
        $facture->setUser($this->getUser());
        $form = $this->createForm(new FactureFournisseurType(), $facture);
        if ($request->isMethod('POST')) {
            try {
                $form->bind($request);
                $facture = $form->getData();
                $montant_ttc = 0;
                foreach ($bons_livraison as $bon_livraison) {
                    $bon_livraison->setFacture($facture);
                    $bon_livraison->setIsCloturer(true);
                    $montant_ttc = $montant_ttc + $bon_livraison->getMontantTtc();
                    $em->persist($bon_livraison);
                }
                $facture->setMontantTtc($montant_ttc + $timbre);
                $facture->setReste($facture->getMontantTtc());
                $facture->setIsCloturer(false);
                $facture->setIsSupprimer(false);
                $heure = $request->get('heure');
                $facture->setHeure($heure);
                $facture->setUser($this->getUser());
                $em->persist($facture);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        return $this->render('GdsAchatBundle:BonLivraison:bons_livraison_to_facture.html.twig', array('form' => $form->createView(), 'timbre' => $timbre, 'bonslivraison' => $bons_livraison));
    }

    function hasBlack($em, $bon_livraison) {
        $lignes = $em->getRepository('GdsVenteBundle:LigneBonLivraisonClient')->findBy(array('bon_livraison' => $bon_livraison));
        foreach ($lignes as $ligne) {
            if ($ligne->getQuantiteNoir() > 0)
                return true;
        }
        return false;
    }

    function fusionner_json($all_articles) {
        $lignes = array();
        $articles = $all_articles->articles;
        $articles_replaced = $all_articles->articles_replaced;
        $cmp = 0;
        foreach ($articles as $article) {
            if ($article->quantite_blanc > 0) {
                $lignes[$cmp]['id'] = $article->id;
                $lignes[$cmp]['quantite'] = $article->quantite_blanc;
                $lignes[$cmp]['prix_vente'] = $article->prix_vente;
                $lignes[$cmp]['taux_tva'] = $article->taux_tva;
                $lignes[$cmp]['remise'] = $article->remise;
                $cmp++;
            }
        }
        foreach ($articles_replaced as $article) {
            $k = $this->is_insered($article, $lignes);
            if ($k != -1) {
                $lignes[$k]['quantite']+=$article->quantite;
            } elseif ($article->quantite > 0) {
                $lignes[$cmp]['id'] = $article->id;
                $lignes[$cmp]['quantite'] = $article->quantite;
                $lignes[$cmp]['prix_vente'] = $article->prix_vente;
                $lignes[$cmp]['taux_tva'] = $article->taux_tva;
                $lignes[$cmp]['remise'] = $article->remise;
                $cmp++;
            }
        }
        return $lignes;
    }

    function is_insered($article, $lignes) {
        foreach ($lignes as $k => $ligne) {
            if ($ligne['id'] == $article->id)
                return $k;
        }
        return -1;
    }

    function stringToDate($date) {
        list($day, $month, $year) = split('/', $date);
        $date = $year . '-' . $month . '-' . $day;
        return new \DateTime($date);
    }

    public function historiqueAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $bon_livraison = $em->getRepository('GdsVenteBundle:BonLivraisonClient')->find($id);
        $reference_bon_livraison = $bon_livraison->getReference();
        $histories = $em->getRepository('GdsVenteBundle:HistoryBonLivraisonClient')->findByReference($reference_bon_livraison);
        return $this->render('GdsVenteBundle:BonLivraison:historiques.html.twig', array('histories' => $histories, 'reference' => $reference_bon_livraison));
    }

    function DateTimeNow() {
        $date = date("Y-m-d H:i:s", time());
        list($a, $b) = split('[ ]', $date);
        list($h, $m, $s) = split('[:]', $b);
        $time = $h * 3600 + $m * 60 + $s;
        $date = new \DateTime('NOW');
        return (array($date, $time));
    }

}

